package com.zshan.clinic.admin.service.medical;

import com.fasterxml.jackson.core.type.TypeReference;
import com.zshan.clinic.admin.constant.Constants;
import com.zshan.clinic.admin.entity.medical.emp.ClinicEmpSimple;
import com.zshan.clinic.admin.entity.medical.order.charge.OrderItemDetail;
import com.zshan.clinic.admin.entity.vo.*;
import com.zshan.clinic.admin.mapper.medical.SpecExamOrderMapper;
import com.zshan.clinic.admin.service.clinic.ClinicEmpService;
import com.zshan.clinic.admin.service.config.ProjectFeeService;
import com.zshan.clinic.admin.service.notice.ClinicNoticeService;
import com.zshan.clinic.admin.task.AsyncTaskService;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.enums.*;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.json.JsonUtil;
import com.zshan.clinic.common.util.page.PageInfo;
import com.zshan.clinic.common.util.page.PageUtils;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.common.util.uuid.IdBuilder;
import com.zshan.clinic.database.dao.OrderExamExecMapper;
import com.zshan.clinic.database.dao.OrderExamMapper;
import com.zshan.clinic.database.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 检查单
 * @author lichen
 */
@Service
@Slf4j
public class OrderExamService {

    @Autowired
    private OrderExamMapper orderExamMapper;

    @Autowired
    private OrderExamExecMapper orderExamExecMapper;

    @Autowired
    private ProjectFeeService projectFeeService;

    @Autowired
    private ClinicEmpService clinicEmpService;

    @Autowired
    private SpecExamOrderMapper specExamOrderMapper;

    @Autowired
    private ClinicNoticeService noticeService;

    @Autowired
    private AsyncTaskService asyncTaskService;

    /**
     * 获取患者检验记录
     * @param clinicId
     * @param patientId
     * @param projectCategory
     * @param visitDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<OrderExamPatientVo> getPatientExamList(Long clinicId, Long patientId, String projectCategory, LocalDate visitDate, Integer pageNo, Integer pageSize) {
        Long totalCount = specExamOrderMapper.getPatientExamCount(clinicId,patientId,projectCategory,visitDate);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<OrderExamPatientVo> examList = specExamOrderMapper.getPatientExamList(clinicId,patientId,projectCategory,visitDate,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,examList);
    }
    /**
     * 查询诊所今日待检查数
     * @param clinicId
     * @return
     */
    public OrderExamWaitingVo getWaitingCount(Long clinicId,String projectCategory) {
        List<OrderExamPageVo> examList = specExamOrderMapper.getWaitingList(clinicId,projectCategory,LocalDate.now());
        if(CollectionUtils.isEmpty(examList)){
            return OrderExamWaitingVo.build();
        }
        Map<String, Long> examMap = examList.stream()
                .map(OrderExamPageVo::getAuditStatus)
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        OrderExamWaitingVo examWaitingVo = new OrderExamWaitingVo();
        examWaitingVo.setPendingCount(examMap.getOrDefault(ExamAuditStatusEnum.PENDING.getValue(), 0L));
        examWaitingVo.setUnderReviewCount(examMap.getOrDefault(ExamAuditStatusEnum.UNDER_REVIEW.getValue(), 0L));
        return examWaitingVo;
    }

    /**
     * 查询患者历史的检查单数量
     * @param clinicId
     * @param patientId
     * @param projectCategory
     * @return
     */
    public Long getOrderExamHistoryCount(Long clinicId, Long patientId, String projectCategory) {
        return specExamOrderMapper.getOrderExamHistoryCount(clinicId,patientId,projectCategory);
    }

    /**
     * 查询患者历史的检查单
     * @param clinicId
     * @param patientId
     * @param projectCategory
     * @param pageNo
     * @param pageSize
     * @return
     */
    public List<OrderExamHistoryVo> getOrderExamHistoryList(Long clinicId,Long patientId,String projectCategory,Integer pageNo, Integer pageSize){
        return specExamOrderMapper.getOrderExamHistoryList(clinicId,patientId,projectCategory,PageUtils.getOffset(pageNo,pageSize),pageSize);
    }

    /**
     * 获取检查单详情
     * @param execId
     * @return
     */
    public OrderExamDetailVo getOrderExamDetail(Long execId){
        return specExamOrderMapper.getOrderExamDetail(execId);
    }

    /**
     * 审核列表
     * @param clinicId
     * @param patientName
     * @param visitDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    public List<OrderExamPageVo> getAuditList(Long clinicId, String projectCategory,String patientName, LocalDate visitDate, Integer pageNo, Integer pageSize){
        //方便调试
//        if(visitDate == null){
//            visitDate = LocalDate.now();
//        }
        if(StringUtil.isNotBlank(patientName)){
            visitDate = null;
        }
        return specExamOrderMapper.getAuditList(clinicId,projectCategory,patientName,visitDate,PageUtils.getOffset(pageNo,pageSize),pageSize);
    }

    /**
     * 检验列表
     * @param clinicId
     * @param patientName
     * @param visitDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    public List<OrderExamPageVo> getExamList(Long clinicId, String projectCategory,String patientName, LocalDate visitDate, Integer pageNo, Integer pageSize){
        //方便调试
//        if(visitDate == null){
//            visitDate = LocalDate.now();
//        }
        if(StringUtil.isNotBlank(patientName)){
            visitDate = null;
        }
        return specExamOrderMapper.getExamList(clinicId,projectCategory,patientName,visitDate,PageUtils.getOffset(pageNo,pageSize),pageSize);
    }

    /**
     * 审核
     * @param orderExamExec
     */
    @Transactional(rollbackFor = Exception.class)
    public void auditExam(OrderExamExec orderExamExec){
        if(StringUtil.isBlank(orderExamExec.getAuditStatus())){
            throw new BusinessFailException("请选择审核状态！");
        }
        if(!ExamAuditStatusEnum.getAuditResultStatus().contains(orderExamExec.getAuditStatus())){
            throw new BusinessFailException("审核状态错误！");
        }
        if(ExamAuditStatusEnum.REJECTED.getValue().equals(orderExamExec.getAuditStatus())){
            if(StringUtil.isBlank(orderExamExec.getRefuseReason())){
                throw new BusinessFailException("请输入拒绝原因！");
            }
            if(orderExamExec.getRefuseReason().length() > Constants.EXAM_REFUSE_REASON_LENGTH){
                throw new BusinessFailException("拒绝原因最多"+Constants.EXAM_REFUSE_REASON_LENGTH+"个字！");
            }
        }
        OrderExamExec dbOrderExamExec = getExecById(orderExamExec.getExecId());
        if(dbOrderExamExec == null){
            throw new BusinessFailException("检查单不存在");
        }
        OrderExam orderExam = getExamById(dbOrderExamExec.getOrderId());
        if(orderExam == null){
            throw new BusinessFailException("检查单不存在");
        }
        if(!ExamAuditStatusEnum.UNDER_REVIEW.getValue().equals(dbOrderExamExec.getAuditStatus())){
            //只有待审核的才能审核
            throw new BusinessFailException("状态不允许");
        }
        dbOrderExamExec.setRefuseReason(orderExamExec.getRefuseReason());
        dbOrderExamExec.setAuditStatus(orderExamExec.getAuditStatus());
        dbOrderExamExec.setAuditUserId(orderExamExec.getUpdateUserId());
        dbOrderExamExec.setAuditBy(orderExamExec.getUpdateBy());
        dbOrderExamExec.setAuditTime(new Date());
        dbOrderExamExec.setUpdateUserId(orderExamExec.getUpdateUserId());
        dbOrderExamExec.setUpdateBy(orderExamExec.getUpdateBy());
        dbOrderExamExec.setUpdateTime(new Date());
        orderExamExecMapper.updateByPrimaryKeySelective(dbOrderExamExec);
        if(ExamAuditStatusEnum.REJECTED.getValue().equals(orderExamExec.getAuditStatus())){
            //如果是审核拒绝，需要发送消息
            ClinicNotice clinicNotice = new ClinicNotice();
            clinicNotice.setEmpId(dbOrderExamExec.getExamEmpId());
            clinicNotice.setNoticeName(Constants.NOTICE_NAME_ORDER_REVIEW);
            clinicNotice.setNoticeContent(String.format(Constants.NOTICE_CONTENT_ORDER_REVIEW,ProjectCategoryEnum.getText(orderExam.getProjectCategory()),orderExam.getOrderNo()));
            clinicNotice.setClinicId(dbOrderExamExec.getClinicId());
            noticeService.addNotice(clinicNotice);
        }
    }

    /**
     * 提交审核
     * @param orderExamExec
     */
    @Transactional(rollbackFor = Exception.class)
    public void submitAudit(OrderExamExec orderExamExec){
        validateExec(orderExamExec);
        OrderExamExec dbOrderExamExec = getExecById(orderExamExec.getExecId());
        if(dbOrderExamExec == null){
            throw new BusinessFailException("检查单不存在");
        }
        OrderExam dbOrderExam = getExamById(dbOrderExamExec.getOrderId());
        if(dbOrderExam == null){
            throw new BusinessFailException("检查单不存在");
        }
        dbOrderExamExec.setExamEmpId(orderExamExec.getExamEmpId());
        dbOrderExamExec.setExamEmpName(orderExamExec.getExamEmpName());
        dbOrderExamExec.setExamDeptId(orderExamExec.getExamDeptId());
        dbOrderExamExec.setExamDeptName(orderExamExec.getExamDeptName());
        dbOrderExamExec.setExamStatus(ExamStatusEnum.CHECKED.getValue());
        dbOrderExamExec.setExamTime(new Date());
        dbOrderExamExec.setExamImageList(orderExamExec.getExamImageList());
        dbOrderExamExec.setExamDesc(orderExamExec.getExamDesc());
        dbOrderExamExec.setDiagnosisFlag(orderExamExec.getDiagnosisFlag());
        dbOrderExamExec.setDiagnosisContent(orderExamExec.getDiagnosisContent());
        dbOrderExamExec.setAuditStatus(ExamAuditStatusEnum.UNDER_REVIEW.getValue());
        dbOrderExamExec.setUpdateUserId(orderExamExec.getUpdateUserId());
        dbOrderExamExec.setUpdateBy(orderExamExec.getUpdateBy());
        dbOrderExamExec.setUpdateTime(new Date());
        orderExamExecMapper.updateByPrimaryKeySelective(dbOrderExamExec);
        //统计诊所今日营收
        StatClinicIncomeDaily statClinicIncomeDaily = new StatClinicIncomeDaily();
        statClinicIncomeDaily.setClinicId(dbOrderExam.getClinicId());
        if(ProjectCategoryEnum.EXAM.getValue().equals(dbOrderExam.getProjectCategory())){
            //检查数+1
            statClinicIncomeDaily.setExamCount(CommonConstant.DEFAULT_1);
        }else if (ProjectCategoryEnum.LAB.getValue().equals(dbOrderExam.getProjectCategory())){
            //检验数+1
            statClinicIncomeDaily.setLabCount(CommonConstant.DEFAULT_1);
        }
        asyncTaskService.asyncSaveOrUpdateClinicIncome(statClinicIncomeDaily);
        if(dbOrderExamExec.getCurrentTimes() >= dbOrderExam.getTotalTimes()){
            //如果当前的次数大于等于总共的次数直接返回，否则需要新生成一个记录
            return;
        }
        //检查有没有生成下一次，如果没有需要新增
        Integer nextTimes = dbOrderExamExec.getCurrentTimes() + CommonConstant.DEFAULT_1;
        Long nextTimesCount = getOrderExamExecByTimes(dbOrderExamExec.getOrderId(),nextTimes);
        if(nextTimesCount > CommonConstant.DEFAULT_0){
            return;
        }
        OrderExamExec nextOrderExamExec = new OrderExamExec();
        nextOrderExamExec.setOrderId(dbOrderExam.getOrderId());
        nextOrderExamExec.setCurrentTimes(nextTimes);
        nextOrderExamExec.setClinicId(dbOrderExamExec.getClinicId());
        nextOrderExamExec.setCreateUserId(dbOrderExamExec.getUpdateUserId());
        nextOrderExamExec.setCreateBy(dbOrderExamExec.getUpdateBy());
        nextOrderExamExec.setCreateTime(new Date());
        insertOrderExamExec(nextOrderExamExec);
    }

    public Long getOrderExamExecByTimes(Long orderId,Integer currentTimes){
        OrderExamExecExample example = new OrderExamExecExample();
        OrderExamExecExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andCurrentTimesEqualTo(currentTimes);
        return orderExamExecMapper.countByExample(example);
    }

    /**
     * 支付成功以后开具对应的检查单
     * @param dbChargeOrder
     * @param examList
     */
    @Transactional(rollbackFor = Exception.class)
    public void createExam(ChargeOrder dbChargeOrder, List<ChargeOrderItem> examList){
        Map<Long, OrderExam> orderExamMap = getOrderItemList(dbChargeOrder,examList);
        if(CollectionUtils.isEmpty(orderExamMap)){
            return;
        }
        addOrUpdateOrderExam(dbChargeOrder.getVisitNo(),orderExamMap);
    }


    /**
     * 保存检查单
     * @param orderExamMap
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdateOrderExam(String visitNo,Map<Long, OrderExam> orderExamMap) {
        if(CollectionUtils.isEmpty(orderExamMap)){
            return;
        }
        List<Long> projectIdList = new ArrayList<>(orderExamMap.keySet());
        //查询所有的检查单
        List<OrderExam> dbOrderExamList = getOrderExamListByVisitNo(visitNo,projectIdList);
        //获取所有的收费项目
        List<ClinicProjectFee> dbProjectList = projectFeeService.getEnabledClinicProjectFeeList(projectIdList,null);
        Date now = new Date();
        for (Map.Entry<Long, OrderExam> entry : orderExamMap.entrySet()) {
            //项目的ID
            Long projectId = entry.getKey();
            //要处理的订单
            OrderExam orderExam = entry.getValue();
            //数据库里已有的订单
            OrderExam dbOrderExam = getDBOrderExam(dbOrderExamList,projectId);
            if(dbOrderExam == null){
                orderExam.setOrderNo(IdBuilder.getUniqueId("JC"));
                ClinicProjectFee clinicProjectFee = getDBProjectFee(dbProjectList,projectId);
                if(clinicProjectFee == null){
                    continue;
                }
                orderExam.setProjectCategory(clinicProjectFee.getProjectCategory());
                orderExam.setProjectType(clinicProjectFee.getProjectType());
                orderExam.setProjectName(clinicProjectFee.getProjectName());
                orderExam.setSampleType(clinicProjectFee.getSampleType());
                orderExam.setOrderTime(now);
                orderExam.setCreateTime(now);
                insertOrderExam(orderExam);
                //先生成一条检查执行记录
                OrderExamExec orderExamExec = new OrderExamExec();
                orderExamExec.setOrderId(orderExam.getOrderId());
                orderExamExec.setCurrentTimes(CommonConstant.DEFAULT_1);
                orderExamExec.setClinicId(orderExam.getClinicId());
                orderExamExec.setCreateUserId(orderExam.getCreateUserId());
                orderExamExec.setCreateBy(orderExam.getCreateBy());
                orderExamExec.setCreateTime(now);
                insertOrderExamExec(orderExamExec);
            }else {
                //更新下单时间
                dbOrderExam.setOrderTime(new Date());
                dbOrderExam.setTotalTimes(dbOrderExam.getTotalTimes() + orderExam.getTotalTimes());
                dbOrderExam.setUpdateUserId(orderExam.getUpdateUserId());
                dbOrderExam.setUpdateBy(orderExam.getUpdateBy());
                dbOrderExam.setUpdateTime(now);
                orderExamMapper.updateByPrimaryKeySelective(dbOrderExam);
                //如果下边的项目都做完了，生成新的检查执行记录
                OrderExamExec lastOrderExamExec = getLastOrderExamExec(dbOrderExam.getOrderId());
                if(ExamStatusEnum.PENDING.getValue().equals(lastOrderExamExec.getExamStatus())){
                    continue;
                }
                //生成一条检查执行记录
                OrderExamExec orderExamExec = new OrderExamExec();
                orderExamExec.setOrderId(dbOrderExam.getOrderId());
                orderExamExec.setCurrentTimes(lastOrderExamExec.getCurrentTimes() + CommonConstant.DEFAULT_1);
                orderExamExec.setClinicId(dbOrderExam.getClinicId());
                orderExamExec.setCreateUserId(dbOrderExam.getUpdateUserId());
                orderExamExec.setCreateBy(dbOrderExam.getUpdateBy());
                orderExamExec.setCreateTime(now);
                insertOrderExamExec(orderExamExec);
            }
        }
    }

    /**
     * 添加检查单
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertOrderExam(OrderExam orderExam){
        if(orderExam.getOrderTime() == null){
            orderExam.setOrderTime(new Date());
        }
        orderExam.setSortNum(CommonConstant.DEFAULT_1);
        orderExam.setIsEnabled(YesOrNoEnum.YES.getValue());
        orderExam.setIsDelete(YesOrNoEnum.NO.getValue());
        if(orderExam.getCreateTime() == null){
            orderExam.setCreateTime(new Date());
        }
        orderExamMapper.insertSelective(orderExam);
    }

    /**
     * 添加检查执行记录
     * @param orderExamExec
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertOrderExamExec(OrderExamExec orderExamExec){
        orderExamExec.setExamStatus(ExamStatusEnum.PENDING.getValue());
        orderExamExec.setAuditStatus(ExamAuditStatusEnum.PENDING.getValue());
        orderExamExec.setSortNum(CommonConstant.DEFAULT_1);
        orderExamExec.setIsEnabled(YesOrNoEnum.YES.getValue());
        orderExamExec.setIsDelete(YesOrNoEnum.NO.getValue());
        if(orderExamExec.getCreateTime() == null){
            orderExamExec.setCreateTime(new Date());
        }
        orderExamExecMapper.insertSelective(orderExamExec);
    }

    public ClinicProjectFee getDBProjectFee(List<ClinicProjectFee> projectFeeList, Long projectId) {
        if(CollectionUtils.isEmpty(projectFeeList)){
            return null;
        }
        for(ClinicProjectFee clinicProjectFee : projectFeeList){
            if(clinicProjectFee.getProjectId().equals(projectId)){
                return clinicProjectFee;
            }
        }
        return null;
    }

    public OrderExam getDBOrderExam(List<OrderExam> orderExamList,Long projectId) {
        if(CollectionUtils.isEmpty(orderExamList)){
            return null;
        }
        for(OrderExam orderExam : orderExamList){
            if(orderExam.getProjectId().equals(projectId)){
                return orderExam;
            }
        }
        return null;
    }

    /**
     * 获取待检查的执行记录
     * @param orderId
     * @return
     */
    public OrderExamExec getLastOrderExamExec(Long orderId){
        OrderExamExecExample example = new OrderExamExecExample();
        OrderExamExecExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOrderByClause("current_times desc");
        List<OrderExamExec> orderExamExecList = orderExamExecMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(orderExamExecList)){
            return null;
        }
        return orderExamExecList.get(0);
    }

    /**
     * 根据诊号和项目查询检查单
     * @param visitNo
     * @param projectIdList
     * @return
     */
    public List<OrderExam> getOrderExamListByVisitNo(String visitNo, List<Long> projectIdList) {
        OrderExamExample example = new OrderExamExample();
        OrderExamExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        criteria.andVisitNoEqualTo(visitNo);
        criteria.andProjectIdIn(projectIdList);
        List<OrderExam> examList = orderExamMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(examList)){
            return null;
        }
        return examList;
    }

    /**
     * 从订单中组合出来检查单
     * @param chargeOrder
     * @param itemList
     * @return
     */
    public Map<Long, OrderExam> getOrderItemList(ChargeOrder chargeOrder, List<ChargeOrderItem> itemList) {
        if (CollectionUtils.isEmpty(itemList)) {
            return null;
        }
        Map<Long, OrderExam> orderExamMap = new LinkedHashMap<>(); // 保证有序
        for (ChargeOrderItem chargeOrderItem : itemList) {
            List<OrderItemDetail> detailList = JsonUtil.json2Obj(chargeOrderItem.getDetailListJson(), new TypeReference<List<OrderItemDetail>>() {});
            if (CollectionUtils.isEmpty(detailList)) {
                continue;
            }
            OrderItemDetail orderItemDetail = detailList.get(0);
            Long projectId = orderItemDetail.getDetailId(); // 可扩展 doctorId 维度
            OrderExam orderExam = orderExamMap.get(projectId);
            if (orderExam == null) {
                orderExam = new OrderExam();
                orderExam.setVisitNo(chargeOrder.getVisitNo());
                orderExam.setVisitDate(chargeOrder.getVisitDate());
                orderExam.setProjectId(orderItemDetail.getDetailId());
                orderExam.setDoctorId(chargeOrderItem.getOrderUserId());
                orderExam.setDoctorName(chargeOrderItem.getOrderBy());
                orderExam.setDeptId(chargeOrderItem.getDeptId());
                orderExam.setDeptName(chargeOrderItem.getDeptName());
                orderExam.setTotalTimes(orderItemDetail.getTotalOutQty());
                orderExam.setPatientId(chargeOrder.getPatientId());
                orderExam.setPatientName(chargeOrder.getPatientName());
                orderExam.setPatientGender(chargeOrder.getPatientGender());
                orderExam.setPatientPhone(chargeOrder.getPatientPhone());
                orderExam.setIdCard(chargeOrder.getIdCard());
                orderExam.setAgeYear(chargeOrder.getAgeYear());
                orderExam.setAgeMonth(chargeOrder.getAgeMonth());
                orderExam.setWeight(chargeOrder.getWeight());
                orderExam.setSystolicBp(chargeOrder.getSystolicBp());
                orderExam.setDiastolicBp(chargeOrder.getDiastolicBp());
                orderExam.setCreateUserId(chargeOrderItem.getCreateUserId());
                orderExam.setCreateBy(chargeOrderItem.getCreateBy());
                orderExam.setClinicId(chargeOrder.getClinicId());
                orderExamMap.put(projectId, orderExam);
            } else {
                orderExam.setUpdateUserId(chargeOrderItem.getCreateUserId());
                orderExam.setUpdateBy(chargeOrderItem.getCreateBy());
                orderExam.setTotalTimes(orderExam.getTotalTimes() + orderItemDetail.getTotalOutQty());
            }
        }
        return orderExamMap;
    }


    /**
     * 分页查询检查单列表
     * @param clinicId 诊所ID
     * @param pageNo 页码
     * @param pageSize 每页条数
     * @return 分页结果
     */
    public PageInfo<OrderExam> getExamListByCondition(Long clinicId, Integer pageNo, Integer pageSize) {
        OrderExamExample example = new OrderExamExample();
        OrderExamExample.Criteria criteria = example.createCriteria();
        if (clinicId != null) {
            criteria.andClinicIdEqualTo(clinicId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = orderExamMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<OrderExam> list = orderExamMapper.selectByExample(example);
        return new PageInfo<>(totalCount, list);
    }

    /**
     * 添加检查单
     * @param orderExam 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void addExam(OrderExam orderExam) {
        validateExam(orderExam);
        orderExam.setSortNum(CommonConstant.DEFAULT_1);
        orderExam.setIsDelete(YesOrNoEnum.NO.getValue());
        orderExam.setIsEnabled(YesOrNoEnum.YES.getValue());
        orderExam.setCreateTime(new Date());
        orderExamMapper.insertSelective(orderExam);
    }

    /**
     * 校验检查单参数
     * @param orderExam 实体
     */
    public void validateExam(OrderExam orderExam) {
        // TODO 添加参数校验逻辑
    }

    /**
     * 根据ID获取检查单详情
     * @param orderId 主键ID
     * @return 实体
     */
    public OrderExam getExamById(Long orderId) {
        if (StringUtil.isBlank(orderId)) {
            return null;
        }
        OrderExam exam = orderExamMapper.selectByPrimaryKey(orderId);
        if (exam == null || YesOrNoEnum.YES.getValue().equals(exam.getIsDelete())) {
            return null;
        }
        return exam;
    }

    /**
     * 修改检查单
     * @param orderExam 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateExam(OrderExam orderExam) {
        validateExam(orderExam);
        OrderExam dbExam = getExamById(orderExam.getOrderId());
        if (dbExam == null) {
            throw new BusinessFailException("检查单不存在");
        }
        orderExam.setUpdateTime(new Date());
        orderExamMapper.updateByPrimaryKeySelective(orderExam);
    }

    /**
     * 删除检查单（逻辑删除）
     * @param orderExam 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteExam(OrderExam orderExam) {
        OrderExam dbExam = getExamById(orderExam.getOrderId());
        if (dbExam == null) {
            throw new BusinessFailException("检查单不存在");
        }
        dbExam.setIsDelete(YesOrNoEnum.YES.getValue());
        dbExam.setUpdateUserId(orderExam.getUpdateUserId());
        dbExam.setUpdateBy(orderExam.getUpdateBy());
        dbExam.setUpdateTime(new Date());
        orderExamMapper.updateByPrimaryKeySelective(dbExam);
    }

    /**
     * 启用检查单
     * @param orderExam 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableExam(OrderExam orderExam) {
        OrderExam dbExam = getExamById(orderExam.getOrderId());
        if (dbExam == null) {
            throw new BusinessFailException("检查单不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbExam.getIsEnabled())) {
            return;
        }
        dbExam.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbExam.setUpdateUserId(orderExam.getUpdateUserId());
        dbExam.setUpdateBy(orderExam.getUpdateBy());
        dbExam.setUpdateTime(new Date());
        orderExamMapper.updateByPrimaryKeySelective(dbExam);
    }

    /**
     * 停用检查单
     * @param orderExam 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableExam(OrderExam orderExam) {
        OrderExam dbExam = getExamById(orderExam.getOrderId());
        if (dbExam == null) {
            throw new BusinessFailException("检查单不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbExam.getIsEnabled())) {
            return;
        }
        dbExam.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbExam.setUpdateUserId(orderExam.getUpdateUserId());
        dbExam.setUpdateBy(orderExam.getUpdateBy());
        dbExam.setUpdateTime(new Date());
        orderExamMapper.updateByPrimaryKeySelective(dbExam);
    }

    /**
     * 分页查询检查单执行记录列表
     * @param clinicId 诊所ID
     * @param pageNo 页码
     * @param pageSize 每页条数
     * @return 分页结果
     */
    public PageInfo<OrderExamExec> getExecListByCondition(Long clinicId, Integer pageNo, Integer pageSize) {
        OrderExamExecExample example = new OrderExamExecExample();
        OrderExamExecExample.Criteria criteria = example.createCriteria();
        if (clinicId != null) {
            criteria.andClinicIdEqualTo(clinicId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = orderExamExecMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<OrderExamExec> list = orderExamExecMapper.selectByExample(example);
        return new PageInfo<>(totalCount, list);
    }

    /**
     * 添加检查单执行记录
     * @param exec 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void addExec(OrderExamExec exec) {
        validateExec(exec);
        exec.setIsDelete(YesOrNoEnum.NO.getValue());
        exec.setIsEnabled(YesOrNoEnum.YES.getValue());
        exec.setCreateTime(new Date());
        orderExamExecMapper.insertSelective(exec);
    }

    /**
     * 校验检查单执行记录参数
     * @param orderExamExec 实体
     */
    public void validateExec(OrderExamExec orderExamExec) {
        // 添加参数校验逻辑
        if(StringUtil.isBlank(orderExamExec.getExamDesc())){
            throw new BusinessFailException("请输入检查描述");
        }
        if(orderExamExec.getExamDesc().length() > Constants.EXAM_DESC_LENGTH){
            throw new BusinessFailException("描述最多"+Constants.EXAM_DESC_LENGTH+"个字！");
        }
        if(StringUtil.isBlank(orderExamExec.getDiagnosisFlag())){
            throw new BusinessFailException("请选择诊断意见");
        }
        if(!DiagnosisFlagEnum.isValue(orderExamExec.getDiagnosisFlag())){
            throw new BusinessFailException("诊断意见错误！");
        }
        if(StringUtil.isBlank(orderExamExec.getDiagnosisContent())){
            throw new BusinessFailException("请输入检查意见内容");
        }
        if(orderExamExec.getDiagnosisContent().length() > Constants.EXAM_DESC_LENGTH){
            throw new BusinessFailException("检查意见内容最多"+Constants.EXAM_DESC_LENGTH+"个字！");
        }
        String examImageList = orderExamExec.getExamImageList();
        if(StringUtil.isNotBlank(examImageList)){
            List<String> imgList = Arrays.asList(examImageList.split(","));
            if(imgList.size() > Constants.EXAM_IMAGE_LIST_LENGTH){
                throw new BusinessFailException("图片最多上传"+Constants.EXAM_IMAGE_LIST_LENGTH+"张！");
            }
        }
        ClinicEmpSimple clinicEmpSimple = clinicEmpService.getEmpSimple(orderExamExec.getClinicId(),orderExamExec.getUpdateUserId());
        if(clinicEmpSimple != null){
            orderExamExec.setExamEmpId(clinicEmpSimple.getEmpId());
            orderExamExec.setExamEmpName(clinicEmpSimple.getEmpName());
            orderExamExec.setExamDeptId(clinicEmpSimple.getDeptId());
            orderExamExec.setExamDeptName(clinicEmpSimple.getDeptName());
        }
    }

    /**
     * 根据ID获取检查单执行记录详情
     * @param execId 主键
     * @return 实体
     */
    public OrderExamExec getExecById(Long execId) {
        if (StringUtil.isBlank(execId)) {
            return null;
        }
        OrderExamExec exec = orderExamExecMapper.selectByPrimaryKey(execId);
        if (exec == null || YesOrNoEnum.YES.getValue().equals(exec.getIsDelete())) {
            return null;
        }
        return exec;
    }

    /**
     * 修改检查单执行记录
     * @param exec 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateExec(OrderExamExec exec) {
        validateExec(exec);
        OrderExamExec dbExec = getExecById(exec.getExecId());
        if (dbExec == null) {
            throw new BusinessFailException("检查单执行记录不存在");
        }
        exec.setUpdateTime(new Date());
        orderExamExecMapper.updateByPrimaryKeySelective(exec);
    }

    /**
     * 删除检查单执行记录（逻辑删除）
     * @param exec 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteExec(OrderExamExec exec) {
        OrderExamExec dbExec = getExecById(exec.getExecId());
        if (dbExec == null) {
            throw new BusinessFailException("检查单执行记录不存在");
        }
        dbExec.setIsDelete(YesOrNoEnum.YES.getValue());
        dbExec.setUpdateUserId(exec.getUpdateUserId());
        dbExec.setUpdateBy(exec.getUpdateBy());
        dbExec.setUpdateTime(new Date());
        orderExamExecMapper.updateByPrimaryKeySelective(dbExec);
    }

    /**
     * 启用检查单执行记录
     * @param exec 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableExec(OrderExamExec exec) {
        OrderExamExec dbExec = getExecById(exec.getExecId());
        if (dbExec == null) {
            throw new BusinessFailException("检查单执行记录不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbExec.getIsEnabled())) {
            return;
        }
        dbExec.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbExec.setUpdateUserId(exec.getUpdateUserId());
        dbExec.setUpdateBy(exec.getUpdateBy());
        dbExec.setUpdateTime(new Date());
        orderExamExecMapper.updateByPrimaryKeySelective(dbExec);
    }

    /**
     * 停用检查单执行记录
     * @param exec 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableExec(OrderExamExec exec) {
        OrderExamExec dbExec = getExecById(exec.getExecId());
        if (dbExec == null) {
            throw new BusinessFailException("检查单执行记录不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbExec.getIsEnabled())) {
            return;
        }
        dbExec.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbExec.setUpdateUserId(exec.getUpdateUserId());
        dbExec.setUpdateBy(exec.getUpdateBy());
        dbExec.setUpdateTime(new Date());
        orderExamExecMapper.updateByPrimaryKeySelective(dbExec);
    }

}
